package cn._51doit.day09;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @create: 2021-10-26 20:42
 * @author: 今晚打脑斧先森
 * @program: EvevtTimeTimer
 * @Description:
 *    只有KeyedStream，使用KeyedProcessFunction才可以使用定时器
 *
 *    使用EventTime注册定时器
 *
 *    OnTimer方法触发的时机 ： WaterMark >= 注册的定时器EventTime时间   注意:在获得warterMark的时候,新的API会减一,旧的API不会
 **/
public class EvevtTimeTimer {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> lines = env.socketTextStream("doit01", 8888);
        //数据: 时间戳,单词,个数
        SingleOutputStreamOperator<String> streamWithWaterMark = lines.assignTimestampsAndWatermarks(WatermarkStrategy
                .<String>forBoundedOutOfOrderness(Duration.ZERO)
                .withTimestampAssigner((line, time) -> Long.parseLong(line.split(",")[0])));
        SingleOutputStreamOperator<Tuple2<String, Integer>> tpStream = streamWithWaterMark.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] split = value.split(",");
                return Tuple2.of(split[1], Integer.parseInt(split[2]));
            }
        });
        //先keyby,在使用定时器
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = tpStream.keyBy(t -> t.f0);
        //使用keyedProcessFunction
        SingleOutputStreamOperator<Tuple2<String, Integer>> res = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            private transient ValueState<List<Tuple2<String, Integer>>> listValueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<List<Tuple2<String, Integer>>> descriptor = new ValueStateDescriptor<>("记录全量数据", TypeInformation.of(new TypeHint<List<Tuple2<String, Integer>>>() {
                }));
                listValueState = getRuntimeContext().getState(descriptor);
            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                List<Tuple2<String, Integer>> list = listValueState.value();
                if (list == null) {
                    list = new ArrayList<>();
                }
                list.add(value);
                listValueState.update(list);

                //直接传进来Watermark不香吗,下面这种方法获得的Watermark是上次的
                long currentWatermark = ctx.timerService().currentWatermark();
                long triggerTime = (currentWatermark - currentWatermark % 60000) + 60000;
                System.out.println(ctx.getCurrentKey() + "注册定时器的时间: " + currentWatermark + " 定时器触发的时间: " + triggerTime);
                //同一个key中,如果出发了多个定时器,只会触发一次,后面的会覆盖前面的
                ctx.timerService().registerEventTimeTimer(triggerTime);
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("触发定时器的时间为: " + timestamp);
                List<Tuple2<String, Integer>> list = listValueState.value();
                for (Tuple2<String, Integer> tp : list) {
                    out.collect(tp);
                }
                list.clear();
            }
        });
        res.print();

        env.execute();
    }
}
